package com.dyrnq.seckill.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.dyrnq.seckill.dto.LoginDTO;
import com.dyrnq.seckill.dto.UserDTO;
import com.dyrnq.seckill.entity.User;
import com.dyrnq.seckill.exception.UnauthorizedException;
import com.dyrnq.seckill.mapper.UserMapper;
import com.dyrnq.seckill.service.IUserService;
import com.dyrnq.seckill.util.MD5Util;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author dyrnq
 * @since 2023-12-06
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {


    private final UserMapper userMapper;

    @Override
    public UserDTO login(LoginDTO loginDTO) {
        User user = userMapper.selectByPhone(loginDTO.getMobile());
        if (user == null) {
            throw new UnauthorizedException("用户名或密码错误");
        }
        UserDTO userDTO = new UserDTO();
        String dbPwd = user.getPassword();
        String calcPass = MD5Util.formPassToDBPass(loginDTO.getPassword(), user.getSalt());
        if (!StringUtils.equals(dbPwd, calcPass)) {
            throw new UnauthorizedException("密码错误");
        }
        userDTO.setUserName(user.getUserName());
        userDTO.setId(user.getId());
        userDTO.setPhone(user.getPhone());
        userDTO.setHead(user.getHead());
        return userDTO;
    }
}
